<!-- 
1 修改页面信息
2 点击图片上传
3 设置用户名校验
  3.1 用户名为空时将提示文本设置为报错信息
  3.2 发出ajax请求
    3.2.1 创建api.php接收请求
    3.2.2 编写查询语句
    3.2.3 连接数据库（导入连接数据库的config.php文件）
    3.2.4 新建functions.php函数库，导入并创建需要的函数，如成功调用函数success，调用失败函数error和查询单条语句函数等
  3.3 账号提示信息为ajax返回信息
4 表单提交用$_POST获取表单参数
  4.1 判断参数是否为空
  4.2 处理密码
  4.3 封装数据
  4.4 处理图片上传
-->
<?php
include_once('config/config.php');
$auth = check_auth();
include_once('./config/logout.php');

if ($_GET) {
	$id= $_GET['id'] ?? '';
	$adminSql = "SELECT * FROM `pre_admin` WHERE `id` = '$id'";
	// var_dump($id);
	$adminData = find($adminSql);
	// var_dump($adminData);
}else{
	showMsg('该管理员不存在');
}
// 判断是否有POST请求
if ($_POST) {
	// 接收参数
	$username = trim($_POST['username']) ?? '';
	$password = trim($_POST['password']) ?? '';
	$repass = trim($_POST['repass']) ?? '';
	$avatar = $_POST['avatar'] ?? '';
	// 判断参数是否为空
	if (empty($username)) {
		showMsg('用户名必填');
	}

	// 通过用户名查询数据表是否存在该用户
	$usernameSql = "SELECT * FROM `pre_admin` WHERE `username` = '$username'";

	$usernameData = find($usernameSql);
	if (empty($username)) {
		showMsg('用户名必填');
	}

	if (empty($password)) {
		showMsg('密码必填');
	}

	if (empty($repass)) {
		showMsg('确认密码必填');
	}

	if ($password != $repass) {
		showMsg('密码与确认密码不一致');
	}

	// 生成密码盐
	$salt = build_randstr();

	// 封装数据
	$data = [
		'username' => $username,
		'password' => md5($password . $salt),
		'salt' => $salt,
		'avatar' => $adminData['avatar']
	];
	
	// 处理图片上传
    if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        $res = build_upload('avatar');

        if ($res['code'] === 0) {
            showMsg($res['msg']);
        }

        $data['avatar'] = $res['data'];
    }
	
	$where = "`id` = '$id'";
	// 插入数据库
	$result = update('admin', $data , $where);

	if ($result['code'] === 1) {
		showMsg('修改管理员成功', 'adminList.php');
	} else {
		// 删除图片
		@is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);

		// 输出错误信息
		echo $result['data'];
		exit;
	}
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
	<?php include_once('common/meta.php'); ?>
</head>

<body>
	<?php include_once('common/header.php'); ?>
	<?php include_once('common/menu.php'); ?>
	<div class="content">
		<div class="header">
			<h1 class="page-title">添加管理员</h1>
		</div>
		<ul class="breadcrumb">
			<li><a href="index.html">Home</a> <span class="divider">/</span></li>
			<li class="active">Index</li>
		</ul>

		<div class="container-fluid">
			<div class="row-fluid">

				<div class="btn-toolbar">
					<button class="btn btn-primary" onClick="location='list.html'"><i class="icon-list"></i> 文章列表</button>
					<div class="btn-group">
					</div>
				</div>

				<div class="well">
					<div id="myTabContent" class="tab-content">
						<div class="tab-pane active in" id="home">
							<form method="post" enctype="multipart/form-data">
								<label>用户名</label>
								<input type="text" id="username" name="username" class="input-xxlarge">
								<span id="username-error"></span>
								<label>修改密码</label>
								<input type="password" id="password" name="password" class="input-xxlarge">
								<label>确认密码</label>
								<input type="password" id="repass" name="repass" class="input-xxlarge">
								<label>头像</label>
								<img src="./assets/images/avatar.png" alt="" id="upload">
								<input type="file" name="avatar" hidden id="avatar">
								<label></label>
								<input class="btn btn-primary" type="submit" value="提交" />
							</form>
						</div>
					</div>
				</div>
				<?php include_once('common/footer.php'); ?>
			</div>
		</div>
	</div>
</body>
<?php include_once('common/script.php'); ?>
<script>
	$('#upload').click(function() {
		$('#avatar').click();
	});
	// 监听上传框的值是否有变化
	$('#avatar').change(function() {
		let file = $(this)[0].files[0];
		// console.log(file);
		if (file) {
			let Reader = new FileReader();

			Reader.readAsDataURL(file);

			Reader.onload = function() {
				$('#upload').attr('src', Reader.result);
			}
		}
	});
	$('input[name="username"]').change(function() {
		let username = $.trim($(this).val());

		if (!username) {
			$('#username-error').text('用户名必填').css({
				color: 'red'
			});
			return;
		}

		$.ajax({
			type: 'post',
			url: 'api.php',
			data: {
				username,
				action: 'check_username'
			},
			dataType: 'json',
			success: function(res) {
				if (res && res.code === 1) {
					$('#username-error').text(res.msg).css({
						color: 'green'
					});
					return;
				} else {
					$('#username-error').text(res.msg).css({
						color: 'red'
					});
					return;
				}
			}
		})
	});
	$('#username').val('<?php echo $adminData['username']; ?>');
	$('#password').val('<?php echo $adminData['password']; ?>');
	$('#repass').val('<?php echo $adminData['password']; ?>');
	$('#upload').attr('src','<?php echo '.'.$adminData['avatar']; ?>');
	</script>

</html>